<?php
namespace app\backend\model;

use app\backend\model\enum\Status;
use app\backend\services\auth\RoleInterface;

class Role extends Base implements RoleInterface
{

    public static $statusLabels
        = [
            Status::STATUS_DISABLE => '禁止',
            Status::STATUS_NORMAL  => '正常',
        ];

    public static $labels
        = [
            'id'            => 'ID',
            'title'         => '名称',
            'status'        => '状态',
            'permissions'   => '权限',
        ];

    protected function getStatusAttr($val)
    {
        return $val == 1;
    }

    protected function setStatusAttr($val)
    {
        return $val ? 1 : 0;
    }

    protected function getPermissionsAttr($val)
    {
        return $val ? json_decode($val, true) : [];
    }

    protected function setPermissionsAttr($val)
    {
        return json_encode($val, JSON_UNESCAPED_UNICODE);
    }

    /**
     * 获取所有可用角色
     *
     * Author: zsw zswemail@qq.com
     */
    public static function getCanList()
    {
        return self::where(['status'=>Status::STATUS_NORMAL])->column('title', 'id');
    }

    public function permissions()
    {
        $permissions = [];
        foreach ($this->permissions as $permission) {
            $permissions[] = explode('.', $permission)[1];
        }

        return $permissions;
    }

}
